package redbencity.com.richtext.richeditor;

import android.text.Spanned;
import android.util.Log;
import android.widget.EditText;


public class TextStyle<T> extends AbstractTextStyle<T> {

    private String TAG = "TextStyle";

    TextStyle(Class<T> spanType, int type) {
        super(spanType, type);
        if (type == TextStyleFactory.BOLD_SPAN || type == TextStyleFactory.ITALIC_SPAN) {
            throw new IllegalArgumentException("must not bold span or italic span");
        }
    }

    @Override
    void cursorPositionChanged(EditText currentEditText, int start, int digits) {
        T[] typeSpans = currentEditText.getEditableText()
                .getSpans(start + digits - 1, start + digits, this.spanType);
        if (typeSpans.length > 0 && typeSpans[0] != null) {
            cursorPositionChangeListener.setCursorPositionChangeListener(this.type);
            isSelect = true;
        }
    }

    @Override
    void inputTextChanged(EditText currentEditText, int start, int count) {
        T[] typeSpans = currentEditText.getEditableText().getSpans(start - 1, start, this.spanType);
        if (typeSpans.length > 0 && typeSpans[0] != null) {
            if (!isSelect) {
                T typeSpan = typeSpans[0];
                int spanStart = currentEditText.getEditableText().getSpanStart(typeSpan);
                int spanEnd = currentEditText.getEditableText().getSpanEnd(typeSpan);
                Log.d(TAG, "  currentEditText.getSelectionStart() " + currentEditText.getSelectionStart()
                        + " spanStart " + spanStart + " spanEnd " + spanEnd + " start " + start + " count " + count);
                currentEditText.getEditableText().removeSpan(typeSpan);
                currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), spanStart, start, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
                if (spanEnd - start - count > 0) {
                    currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), start + count, spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
                }
            }
        } else {
            if (isSelect) {
                currentEditText.getEditableText().setSpan(TextStyleFactory.createCharacter(this.type), start, start + count, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            }
        }
    }
}


